<?php

namespace app\utils;

use think\facade\Request;
use app\model\User;
use think\facade\Db;
use think\facade\Cache;


class Adminapi
{
    // --- 页面加载 ---
    public static function get_pages() // 获取页面
    {
        if (Utils::has_admin("") == false) {
            return Utils::api_response(200, '获取成功', array());
        }
        $categories = json_decode(file_get_contents("../view/admin/pages.json"));
        $return = array();
        foreach ($categories as $cate) {
            $cate_id = $cate[1];
            $cate_content = $cate[2];
            $cate_content_ = array();
            foreach ($cate_content as $group) {
                $group_id = $group[1];
                $group_content = $group[2];
                if (gettype($group_content) == "string") {
                    if (Utils::has_admin("$cate_id/$group_id")) {
                        array_push($cate_content_, $group);
                    }
                } else {
                    $group_content_ = array();
                    foreach ($group_content as $page) {
                        $page_id = $page[1];
                        if (Utils::has_admin("$cate_id/$group_id/$page_id")) {
                            array_push($group_content_, $page);
                        }
                    }
                    if (count($group_content_) != 0) {
                        array_push($cate_content_, array($group[0], $group_id, $group_content_));
                    }
                }
            }
            if (count($cate_content_) != 0) {
                array_push($return, array($cate[0], $cate_id, $cate_content_));
            }
        }
        return Utils::api_response(200, '获取成功', $return);
    }

    // --- 首页 ---

    // --- 用户组 ---
    public static function get_group_list()
    {
        if (!Utils::has_admin("user/group")) {
            return false;
        }

        $pagecut = 20;
        $p = Request::get('p');

        $sort_field = Request::get('sort_field', 'id');
        $sort_field_can = array('id', 'title');
        $sort_type = Request::get('sort_type', '1');

        $where_id = Request::get('where_id', '');
        $where_name = Request::get('where_name', '');
        $where_desc = Request::get('where_desc', '');
        $where_create_time = Request::get('where_create_time', '');

        if (!in_array($sort_field, $sort_field_can) || ($sort_type != '0' && $sort_type != '1')) {
            return Utils::api_response(400, '参数有误');
        }

        $group = Db::table('site_user_group')->where([
            ...(($where_id !== '') ? [['id', '=', intval($where_id)]] : []),
            ['title', 'like', '%' . $where_name . '%']
        ])->field('id,title')->order([
            $sort_field => $sort_type == '1' ? 'desc' : 'asc'
        ]);

        $pages = count($group->select()->toArray());
        $pages = $pages % $pagecut == 0 ? $pages / $pagecut : ceil($pages / $pagecut);

        $page_data = $group->page(intval($p), $pagecut)->select()->toArray();

        return Utils::api_response(200, '获取成功', array("data" => $page_data, "size" => $pages));
    }

    public static function get_group_data()
    {
        if (!Utils::has_admin("user/group")) {
            return false;
        }

        $id = intval(Request::get('id'));
        $group = Db::table('site_user_group')->where('id', $id)->field('id,title')->find();
        if (!$group) {
            return Utils::api_response(400, '组不存在');
        }


        return Utils::api_response(200, '获取成功', $group);
    }

    public static function save_group()
    {
        if (!Utils::has_admin("user/group")) {
            return false;
        }

        $id = intval(Request::post('id'));
        $title = Request::post('title');

        if (!$title) {
            return Utils::api_response(400, '组标题不能为空');
        }

        $group = Db::table('site_user_group')->where('id', $id)->find();
        if (!$group) {
            return Utils::api_response(400, '组不存在');
        }

        Db::table('site_user_group')->where('id', $id)->update([
            'title' => $title
        ]);

        return Utils::api_response(200, '保存成功');
    }

    public static function get_group_members()
    {
        if (!Utils::has_admin("user/group")) {
            return false;
        }

        $group_id = intval(Request::get('id'));
        $members = Db::table('site_user_group_user_list')
            ->alias('ugul')
            ->join('site_user u', 'ugul.user_id = u.id')
            ->where('ugul.group_id', $group_id)
            ->field('u.id, u.name, u.img')
            ->select()->toArray();

        return Utils::api_response(200, '获取成功', $members);
    }

    public static function delete_group()
    {
        if (!Utils::has_admin("user/group")) {
            return false;
        }

        $id = intval(Request::post('id'));
        Db::table('site_user_group')->where('id', $id)->delete();
        Db::table('site_user_group_user_list')->where('group_id', $id)->delete();


        return Utils::api_response(200, '删除成功');
    }

    // --- 用户 ---
    public static function get_user_list() // 获取用户列表
    {
        if (!Utils::has_admin("user/list")) {
            return false;
        }

        $pagecut = 20;
        $p = Request::get('p');

        $sort_field = Request::get('sort_field', 'id');
        $sort_field_can = array('id', 'name', 'time');
        $sort_type = Request::get('sort_type', '1');

        $where_id = Request::get('where_id', '');
        $where_bcm_id = Request::get('where_bcm_id', '');
        $where_name = Request::get('where_name', '');
        $where_email = Request::get('where_email', '');

        // 如果 $sort_field_can 不包含 $sort_field 或 $sort_type 不是 0 或 1 则返回错误
        if (!in_array($sort_field, $sort_field_can) || ($sort_type != '0' && $sort_type != '1')) {
            return Utils::api_response(400, '参数有误');
        }

        $user = User::where([
            ...(($where_id !== '') ? [['id', '=', intval($where_id)]] : []),
            ...(($where_bcm_id !== '') ? [['bcm_id', '=', intval($where_bcm_id)]] : []),
            ['name', 'like', '%' . $where_name . '%'],
            ['email', 'like', '%' . $where_email . '%']
        ])->field('id,name,img,bcm_id,email,time')->order([
            $sort_field => $sort_type == '1' ? 'desc' : 'esc'
        ]);

        // 计算总页数
        $pages = count($user->select()->toArray());
        if ($pages % $pagecut == 0) {
            $pages = $pages / $pagecut;
        } else {
            $pages = ceil($pages / $pagecut);
        }

        // 进行数据分页
        $page_data = $user->page(intval($p), $pagecut)->select()->toArray();
        $result = array();
        foreach ($page_data as $key) {
            $result[] = $key;
        }

        return Utils::api_response(200, '获取成功', array("data" => $result, "size" => $pages));
    }

    public static function get_user_data() // 获取用户详细信息
    {
        if (!Utils::has_admin("user/list")) {
            return false;
        }

        $id = intval(Request::get('id'));
        $user = User::where('id', $id)
            ->withoutField('password,token,admin') // 排除字段
            ->find()->toArray();
        if (count($user) == 0) {
            return Utils::api_response(400, '用户不存在');
        }

        $post_count = Db::table('site_post')->where('user_id', $id)->field('COUNT(*) AS a')->find(); // 帖子数量
        $talk_count = Db::table('site_talk')->where('user_id', $id)->field('COUNT(*) AS a')->find(); // 评论数量
        $good_count = Db::table('site_goods')->where('user_id', $id)->field('COUNT(*) AS a')->find(); // 献赞数量
        $get_good_count = Db::table('site_post')->where('user_id', $id)->field('SUM(goods) AS a')->find(); // 获赞数量
        $get_view_count = Db::table('site_post')->where('user_id', $id)->field('SUM(views) AS a')->find(); // 获阅数量

        $last_info = Db::table('site_token')->where('user_id', $id)->order('time', 'desc')->find(); // 最后登录信息
        if ($last_info) {
            $user['last_time'] = $last_info['time'];
            $user['last_ip'] = $last_info['ip'];
            $user['ua'] =  $last_info['ua'];
        } else {
            $user['last_time'] = null;
            $user['last_ip'] = null;
            $user['ua'] = null;
        }

        $user['post_count'] = intval($post_count['a']);
        $user['talk_count'] = intval($talk_count['a']);
        $user['good_count'] = intval($good_count['a']);
        $user['get_good_count'] = intval($get_good_count['a']);
        $user['get_view_count'] = intval($get_view_count['a']);

        return Utils::api_response(200, '获取成功', $user);
    }

    public static function change_user_data() // 获取用户详细信息
    {
        if (!Utils::has_admin("user/list")) {
            return false;
        }

        $id = intval(Request::post('id'));
        $name = Request::post('name', null);
        $img = Request::post('img', null);
        $email = Request::post('email', null);
        $bcm_id = Request::post('bcm_id', 0);

        if (!$bcm_id) $bcm_id = 0;

        $user = User::where('id', $id)->find();
        if ($user->isEmpty()) {
            return Utils::api_response(400, '用户不存在');
        }
        if (!$name || !$img || !$email) { // 长度过大
            return Utils::api_response(400, '参数不足');
        }

        if (mb_strlen($name) > 50 || mb_strlen($img) > 8182) { // 长度过大
            return Utils::api_response(400, '字数过多');
        }

        // 如果要更改昵称并且昵称已经存在
        if ($user->name !== $name && User::hasName($name)) {
            return json(array("code" => 400, 'msg' => '昵称已存在'));
        }

        $user->name = $name;
        $user->img = $img;
        $user->email = $email;
        $user->bcm_id = intval($bcm_id);
        $user->save();

        return Utils::api_response(200, '更新成功');
    }

    public static function ban_user() //禁用
    {
        if (!Utils::has_admin("user/list")) {
            return false;
        }
        $time = intval(Request::post('time'));
        if ($time == -1) {
            //解禁
            Cache::delete(md5("uid_" . Request::post('id')));
            return Utils::api_response(200, '成功');
        }
        Cache::set(md5("uid_" . Request::post('id')), true, $time);
        $token = Db::table('site_token')->where('user_id', Request::post('id'))->select()->toArray();
        foreach ($token as $key) {
            //过滤token的非法字符，只允许字母和数字
            $key["token"] = preg_replace('/[^a-zA-Z0-9]/', '', $key["token"]);
            unlink("../runtime/session/sess_" . $key["token"]);
        }
        Db::table('site_token')->where('user_id', Request::post('id'))->delete();
        return Utils::api_response(200, '成功');
    }

    // --- 社区 ---    
    public static function get_post_list() // 获取帖子列表
    {
        if (!Utils::has_admin("shequ/post")) {
            return false;
        }

        $pagecut = 20;
        $p = Request::get('p');

        $sort_field = Request::get('sort_field', 'id');
        $sort_field_can = array('id', 'title', 'time', 'views', 'goods');
        $sort_type = Request::get('sort_type', '1');

        $where_id = Request::get('where_id', '');
        $where_partition = Request::get('where_partition', '');
        $where_search = Request::get('where_search', '');
        $where_user_id = Request::get('where_user_id', '');

        // 如果 $sort_field_can 不包含 $sort_field 或 $sort_type 不是 0 或 1 则返回错误
        if (!in_array($sort_field, $sort_field_can) || ($sort_type != '0' && $sort_type != '1')) {
            return Utils::api_response(400, '参数有误');
        }

        $posts = Db::table('site_post')->where([
            ...(($where_id !== '') ? [['id', '=', intval($where_id)]] : []),
            ...(($where_user_id !== '') ? [['user_id', '=', intval($where_user_id)]] : []),
            ...(($where_partition !== '') ? [['post_partition', '=', intval($where_partition)]] : []),

            ['title|text', 'like', '%' . $where_search . '%']
        ])->field('id,title,views,goods,time,user_id,ishot,isbest,ison,post_partition,ban')->order([
            $sort_field => $sort_type == '1' ? 'desc' : 'esc'
        ]);

        // 计算总页数
        $pages = count($posts->select()->toArray());
        if ($pages % $pagecut == 0) {
            $pages = $pages / $pagecut;
        } else {
            $pages = ceil($pages / $pagecut);
        }

        // 进行数据分页
        $page_data = $posts->page(intval($p), $pagecut)->select()->toArray();
        $result = array();
        foreach ($page_data as $key) {
            $userinfo = User::where('id', $key['user_id'])->find(); // 查询数据
            $key["user_img"] = $userinfo['img'];
            $key["user_name"] = $userinfo['name'];

            $partition = Db::table('site_post_partition')->where('id', $key['post_partition'])->find();
            $key['post_partition_name'] = $partition['name'];

            $result[] = $key;
        }

        return Utils::api_response(200, '获取成功', array("data" => $result, "size" => $pages));
    }

    public static function get_post_info() // 获取帖子详细信息
    {
        if (!Utils::has_admin("shequ/post")) {
            return false;
        }

        $post_id = intval(Request::get('id'));

        $post = Db::table('site_post')->where('id', $post_id)->field('id,title,text,views,goods,time,user_id,ip,post_partition')->find();
        if (!$post) {
            return Utils::api_response(404, '帖子不存在');
        }

        $userinfo = User::where('id', $post['user_id'])->find(); // 查询数据
        $post["user_name"] = $userinfo['name'];

        $partition = Db::table('site_post_partition')->where('id', $post['post_partition'])->find();
        $post['post_partition_name'] = $partition['name'];

        $talks_count = 0;
        $talks = Db::table('site_talk')->where('post_id', $post_id)->field('id')->select()->toArray();
        $talks_count += count($talks);
        foreach ($talks as $key) {
            $talk_c = Db::table('site_talk')->where('talk_id', $key['id'])->field('COUNT(*) as a')->find();
            $talks_count += $talk_c['a'] || 0;
        }

        $post['talks'] = $talks_count;

        return Utils::api_response(200, '获取成功', $post);
    }

    public static function change_post_info() // 更改
    {
        if (!Utils::has_admin("shequ/post")) {
            return false;
        }

        $post_id = intval(Request::post('id'));

        $post = Db::table('site_post')->where('id', $post_id)->field('id')->find();
        if (!$post) {
            return Utils::api_response(404, '帖子不存在');
        }

        $change_data = array();

        // 设置 标题和内容
        $change_title = Request::post('title', null);
        $change_text = Request::post('text', null);

        if ($change_title) {
            if (mb_strlen($change_title) > 100) { // 长度过大
                return Utils::api_response(400, '字数过多');
            }
            $change_data['title'] = $change_title;
        };
        if ($change_text) {
            if (mb_strlen($change_text) > 100000) { // 长度过大
                return Utils::api_response(400, '字数过多');
            }
            $change_data['text'] = $change_text;
        };

        // 设置 是否置顶、是否精华、是否热门
        $change_ison = Request::post('ison', null);
        $change_isbest = Request::post('isbest', null);
        $change_ishot = Request::post('ishot', null);

        if ($change_ison) $change_data['ison'] = $change_ison == 'true' ? 1 : 0;
        if ($change_isbest) $change_data['isbest'] = $change_isbest == 'true' ? 1 : 0;
        if ($change_ishot) $change_data['ishot'] = $change_ishot == 'true' ? 1 : 0;

        // 设置 分区、用户id、是否封禁
        $change_post_partition = Request::post('post_partition', null);
        $change_user_id = Request::post('user_id', null);
        $change_ban = Request::post('ban', null);

        if ($change_post_partition) {
            // 查看分区是否存在
            $partition = Db::table('site_post_partition')->where('id', intval($change_post_partition))->find();
            if (!$partition) {
                return Utils::api_response(400, '分区不存在');
            }
            $change_data['post_partition'] = intval($change_post_partition);
        };
        if ($change_user_id) {
            $user = User::where('id', intval($change_user_id))->find();
            if (!$user) {
                return Utils::api_response(400, '用户不存在');
            }
            $change_data['user_id'] = intval($change_user_id);
        }

        if ($change_ban) $change_data['ban'] = $change_ban == 'true' ? 1 : 0;

        // 如果没有要更新
        if (count($change_data) == 0) {
            return Utils::api_response(400, '参数不足');
        }

        // 更新内容
        Db::table('site_post')->where('id', $post_id)->update($change_data);

        return Utils::api_response(200, '修改成功');
    }

    public static function delete_post() // 删除帖子
    {
        if (!Utils::has_admin("shequ/post")) {
            return false;
        }

        $post_id = intval(Request::post('id'));

        $post = Db::table('site_post')->where('id', $post_id)->field('id')->find();
        if (!$post) {
            return Utils::api_response(404, '帖子不存在');
        }

        Db::table('site_post')->where('id', $post_id)->delete();
        return Utils::api_response(200, '删除成功');
    }

    public static function get_talk_list() // 获取评论列表
    {
        if (!Utils::has_admin("shequ/talk")) {
            return false;
        }

        $pagecut = 20;
        $p = Request::get('p');

        $sort_field = Request::get('sort_field', 'id');
        $sort_field_can = array('id', 'time');
        $sort_type = Request::get('sort_type', '1');

        $where_id = Request::get('where_id', '');
        $where_post_id = Request::get('where_post_id', '');
        $where_talk_id = Request::get('where_talk_id', '');
        $where_user_id = Request::get('where_user_id', '');
        $where_search = Request::get('where_search', '');

        if (!in_array($sort_field, $sort_field_can) || ($sort_type != '0' && $sort_type != '1')) {
            return Utils::api_response(400, '参数有误');
        }

        $talks = Db::table('site_talk')->where([
            ...(($where_id !== '') ? [['id', '=', intval($where_id)]] : []),
            ...(($where_post_id !== '') ? [['post_id', '=', intval($where_post_id)]] : []),
            ...(($where_talk_id !== '') ? [['talk_id', '=', intval($where_talk_id)]] : []),
            ...(($where_user_id !== '') ? [['user_id', '=', intval($where_user_id)]] : []),
            ['text', 'like', '%' . $where_search . '%']
        ])->field('id,user_id,post_id,text,time,ip,talk_id')->order([
            $sort_field => $sort_type == '1' ? 'desc' : 'esc'
        ]);

        $pages = count($talks->select()->toArray());
        if ($pages % $pagecut == 0) {
            $pages = $pages / $pagecut;
        } else {
            $pages = ceil($pages / $pagecut);
        }

        $page_data = $talks->page(intval($p), $pagecut)->select()->toArray();
        $result = array();
        foreach ($page_data as $key) {
            $userinfo = User::where('id', $key['user_id'])->find();
            $key["user_img"] = $userinfo['img'];
            $key["user_name"] = $userinfo['name'];

            if ($key['post_id']) {
                $post = Db::table('site_post')->where('id', $key['post_id'])->find();
                $key['post_title'] = $post ? $post['title'] : '未知帖子';
            }

            $result[] = $key;
        }

        return Utils::api_response(200, '获取成功', array("data" => $result, "size" => $pages));
    }

    public static function get_talk_info() // 获取评论详细信息
    {
        if (!Utils::has_admin("shequ/talk")) {
            return false;
        }

        $talk_id = intval(Request::get('id'));

        $talk = Db::table('site_talk')->where('id', $talk_id)->field('id,text,time,user_id,ip,post_id,talk_id')->find();
        if (!$talk) {
            return Utils::api_response(404, '评论不存在');
        }

        $userinfo = User::where('id', $talk['user_id'])->find(); // 查询数据
        $talk["user_name"] = $userinfo['name'];

        if ($talk['post_id']) {
            $post = Db::table('site_post')->where('id', $talk['post_id'])->find();
            $talk['post_title'] = $post['title'];
        }

        return Utils::api_response(200, '获取成功', $talk);
    }

    public static function change_talk_info() // 更改
    {
        if (!Utils::has_admin("shequ/talk")) {
            return false;
        }

        $talk_id = intval(Request::post('id'));

        $post = Db::table('site_talk')->where('id', $talk_id)->field('id')->find();
        if (!$post) {
            return Utils::api_response(404, '评论不存在');
        }

        $change_data = array();

        // 设置 标题和内容
        $change_text = Request::post('text', null);

        if ($change_text) {
            if (mb_strlen($change_text) > 100000) { // 长度过大
                return Utils::api_response(400, '字数过多');
            }
            $change_data['text'] = $change_text;
        };

        // 如果没有要更新
        if (count($change_data) == 0) {
            return Utils::api_response(400, '参数不足');
        }

        // 更新内容
        Db::table('site_talk')->where('id', $talk_id)->update($change_data);

        return Utils::api_response(200, '修改成功');
    }

    public static function delete_talk() // 删除评论
    {
        if (!Utils::has_admin("shequ/talk")) {
            return false;
        }

        $id = intval(Request::post('id'));
        $talk = Db::table('site_talk')->where('id', $id)->find();
        if (!$talk) {
            return Utils::api_response(404, '评论不存在');
        }

        // 删除子评论
        Db::table('site_talk')->where('talk_id', $id)->delete();
        // 删除主评论
        Db::table('site_talk')->where('id', $id)->delete();

        return Utils::api_response(200, '删除成功');
    }

    // --- 轮播图管理 ---


    // --- 新品管理 ---
    public static function get_new_things_list() // 获取新品列表
    {
        if (!Utils::has_admin("new_things/list")) {
            return false;
        }

        $pagecut = 20;
        $p = Request::get('p', 1);
        $sort_field = Request::get('sort_field', 'id');
        $sort_field_can = array('id', 'name', 'url');
        $sort_type = Request::get('sort_type', '1');

        $where_id = Request::get('where_id', '');
        $where_name = Request::get('where_name', '');
        $where_url = Request::get('where_url', '');
        $where_search = Request::get('where_search', '');

        if (!in_array($sort_field, $sort_field_can) || ($sort_type != '0' && $sort_type != '1')) {
            return Utils::api_response(400, '参数有误');
        }

        $newThings = Db::table('site_new_things')->where([
            ...(($where_id !== '') ? [['id', '=', intval($where_id)]] : []),
            ['name', 'like', '%' . $where_name . '%'],
            ['url', 'like', '%' . $where_url . '%'],
            ...(($where_search !== '') ? [[['name', 'like', '%' . $where_search . '%'], ['url', 'like', '%' . $where_search . '%'], 'or']] : [])
        ])->order([
            $sort_field => $sort_type == '1' ? 'desc' : 'asc'
        ]);

        $pages = count($newThings->select()->toArray());
        if ($pages % $pagecut == 0) {
            $pages = $pages / $pagecut;
        } else {
            $pages = ceil($pages / $pagecut);
        }

        $page_data = $newThings->page(intval($p), $pagecut)->select()->toArray();

        return Utils::api_response(200, '获取成功', array("data" => $page_data, "size" => $pages));
    }

    public static function add_new_thing() // 添加新品
    {
        if (!Utils::has_admin("new_things/add")) {
            return false;
        }

        $name = Request::post('name');
        $url = Request::post('url');

        if (!$name || !$url) {
            return Utils::api_response(400, '名称和URL不能为空');
        }

        if (mb_strlen($name) > 50) {
            return Utils::api_response(400, '名称过长');
        }

        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            return Utils::api_response(400, 'URL格式不正确');
        }

        $id = Db::table('site_new_things')->insertGetId([
            'name' => $name,
            'url' => $url,
            'create_time' => time()
        ]);

        return Utils::api_response(200, '添加成功', ['id' => $id]);
    }

    public static function change_new_thing_info() // 修改新品
    {
        if (!Utils::has_admin("new_things/edit")) {
            return false;
        }

        $id = intval(Request::post('id'));
        $name = Request::post('name');
        $url = Request::post('url');

        $newThing = Db::table('site_new_things')->where('id', $id)->find();
        if (!$newThing) {
            return Utils::api_response(404, '新品不存在');
        }

        if (!$name || !$url) {
            return Utils::api_response(400, '名称和URL不能为空');
        }

        if (mb_strlen($name) > 50) {
            return Utils::api_response(400, '名称过长');
        }

        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            return Utils::api_response(400, 'URL格式不正确');
        }

        Db::table('site_new_things')->where('id', $id)->update([
            'name' => $name,
            'url' => $url,
            'update_time' => time()
        ]);

        return Utils::api_response(200, '修改成功');
    }

    public static function delete_new_thing() // 删除新品
    {
        if (!Utils::has_admin("new_things/delete")) {
            return false;
        }

        $id = intval(Request::post('id'));
        $newThing = Db::table('site_new_things')->where('id', $id)->find();
        if (!$newThing) {
            return Utils::api_response(404, '新品不存在');
        }

        Db::table('site_new_things')->where('id', $id)->delete();
        return Utils::api_response(200, '删除成功');
    }

    // --- 轮播图管理 ---
    public static function get_banner_list() // 获取轮播图列表
    {
        if (!Utils::has_admin("banner/list")) {
            return false;
        }

        $pagecut = 20;
        $p = Request::get('p', 1);
        $sort_field = Request::get('sort_field', 'id');
        $sort_field_can = array('id', 'img', 'url');
        $sort_type = Request::get('sort_type', '1');
        $where_id = Request::get('where_id', '');
        $where_url = Request::get('where_url', '');
        $where_search = Request::get('where_search', '');

        if (!in_array($sort_field, $sort_field_can) || ($sort_type != '0' && $sort_type != '1')) {
            return Utils::api_response(400, '参数有误');
        }

        $banner = Db::table('site_banner')->where([
            ...(($where_id !== '') ? [['id', '=', intval($where_id)]] : []),
            ['url', 'like', '%' . $where_url . '%'],
            ...(($where_search !== '') ? [[['img', 'like', '%' . $where_search . '%'], ['url', 'like', '%' . $where_search . '%'], 'or']] : [])
        ])->order([
            $sort_field => $sort_type == '1' ? 'desc' : 'asc'
        ]);

        // 计算总页数
        $pages = count($banner->select()->toArray());
        if ($pages % $pagecut == 0) {
            $pages = $pages / $pagecut;
        } else {
            $pages = ceil($pages / $pagecut);
        }

        // 进行数据分页
        $page_data = $banner->page(intval($p), $pagecut)->select()->toArray();

        return Utils::api_response(200, '获取成功', array("data" => $page_data, "size" => $pages));
    }

    public static function get_banner_info() // 获取轮播图信息
    {
        if (!Utils::has_admin("banner/list")) {
            return false;
        }

        $id = intval(Request::get('id'));
        $banner = Db::table('site_banner')->where('id', $id)->find();
        if (!$banner) {
            return Utils::api_response(404, '轮播图不存在');
        }

        return Utils::api_response(200, '获取成功', $banner);
    }

    public static function add_banner() // 添加轮播图
    {
        if (!Utils::has_admin("banner/add")) {
            return false;
        }

        $img_url = Request::post('img_url', '');
        if (!$img_url) {
            return Utils::api_response(400, '图片URL不能为空');
        }
        // 简单验证URL格式
        if (!filter_var($img_url, FILTER_VALIDATE_URL)) {
            return Utils::api_response(400, '图片URL格式不正确');
        }
        $url = Request::post('url', '');

        if (!$url) {
            return Utils::api_response(400, 'URL不能为空');
        }

        $id = Db::table('site_banner')->insertGetId([
            'img' => $img_url,
            'url' => $url
        ]);

        return Utils::api_response(200, '添加成功', ['id' => $id]);
    }

    public static function change_banner_info() // 修改轮播图
    {
        if (!Utils::has_admin("banner/edit")) {
            return false;
        }

        $id = intval(Request::post('id'));
        $banner = Db::table('site_banner')->where('id', $id)->find();
        if (!$banner) {
            return Utils::api_response(404, '轮播图不存在');
        }

        $data = [];
        $url = Request::post('url', '');
        if ($url) {
            $data['url'] = $url;
        }

        $img_url = Request::post('img_url', '');
        if ($img_url) {
            // 简单验证URL格式
            if (!filter_var($img_url, FILTER_VALIDATE_URL)) {
                return Utils::api_response(400, '图片URL格式不正确');
            }
            $data['img'] = $img_url;
        }

        if (empty($data)) {
            return Utils::api_response(400, '没有需要更新的内容');
        }

        Db::table('site_banner')->where('id', $id)->update($data);
        return Utils::api_response(200, '修改成功');
    }

    public static function delete_banner() // 删除轮播图
    {
        if (!Utils::has_admin("banner/delete")) {
            return false;
        }

        $id = intval(Request::post('id'));
        $banner = Db::table('site_banner')->where('id', $id)->find();
        if (!$banner) {
            return Utils::api_response(404, '轮播图不存在');
        }

        // 删除图片文件
        if (file_exists('../public' . $banner['img'])) {
            @unlink('../public' . $banner['img']);
        }

        Db::table('site_banner')->where('id', $id)->delete();
        return Utils::api_response(200, '删除成功');
    }

    public static function get_nav_list() // 获取导航列表
    {
        if (!Utils::has_admin("nav/list")) {
            return false;
        }

        $pagecut = 20;
        $p = Request::get('p', 1);
        $sort_field = Request::get('sort_field', 'id');
        $sort_field_can = array('id', 'name', 'url');
        $sort_type = Request::get('sort_type', '1');
        $where_id = Request::get('where_id', '');
        $where_name = Request::get('where_name', '');
        $where_url = Request::get('where_url', '');
        $where_search = Request::get('where_search', '');

        if (!in_array($sort_field, $sort_field_can) || ($sort_type != '0' && $sort_type != '1')) {
            return Utils::api_response(400, '参数有误');
        }

        $nav = Db::table('site_nav')->where([
            ...(($where_id !== '') ? [['id', '=', intval($where_id)]] : []),
            ['name', 'like', '%' . $where_name . '%'],
            ['url', 'like', '%' . $where_url . '%'],
            ...(($where_search !== '') ? [[['name', 'like', '%' . $where_search . '%'], ['url', 'like', '%' . $where_search . '%'], 'or']] : [])
        ])->order([
            $sort_field => $sort_type == '1' ? 'desc' : 'asc'
        ]);

        $total = count($nav->select()->toArray());
        $pages = $total % $pagecut == 0 ? $total / $pagecut : ceil($total / $pagecut);
        $data = $nav->page(intval($p), $pagecut)->select()->toArray();

        return Utils::api_response(200, '获取成功', array("data" => $data, "size" => $pages));
    }

    public static function get_nav_info() {
        if (!Utils::has_admin("nav/read")) {
            return Utils::api_response(403, '无权限');
        }

        $id = intval(Request::get('id'));
        if (!$id) {
            return Utils::api_response(400, 'ID不能为空');
        }

        $nav = Db::table('site_nav')->where('id', $id)->find();
        if (!$nav) {
            return Utils::api_response(404, '导航不存在');
        }

        return Utils::api_response(200, 'success', $nav);
    }

    public static function add_nav() {
        if (!Utils::has_admin("nav/add")) {
            return Utils::api_response(403, '无权限');
        }

        $name = Request::post('name', '');
        $url = Request::post('url', '');

        if (empty($name) || empty($url)) {
            return Utils::api_response(400, '名称和URL不能为空');
        }

        $id = Db::table('site_nav')->insertGetId([
            'name' => $name,
            'url' => $url,
            'create_time' => time()
        ]);

        if (!$id) {
            return Utils::api_response(500, '添加失败');
        }

        return Utils::api_response(200, '添加成功', ['id' => $id]);
    }

    public static function change_nav_info() {
        if (!Utils::has_admin("nav/edit")) {
            return Utils::api_response(403, '无权限');
        }

        $id = intval(Request::post('id'));
        $name = Request::post('name', '');
        $url = Request::post('url', '');

        if (!$id || empty($name) || empty($url)) {
            return Utils::api_response(400, 'ID、名称和URL不能为空');
        }

        $nav = Db::table('site_nav')->where('id', $id)->find();
        if (!$nav) {
            return Utils::api_response(404, '导航不存在');
        }

        Db::table('site_nav')->where('id', $id)->update([
            'name' => $name,
            'url' => $url,
            
        ]);

        return Utils::api_response(200, '修改成功');
    }

    public static function delete_nav() {
        if (!Utils::has_admin("nav/delete")) {
            return Utils::api_response(403, '无权限');
        }

        $id = intval(Request::post('id'));
        if (!$id) {
            return Utils::api_response(400, 'ID不能为空');
        }

        $nav = Db::table('site_nav')->where('id', $id)->find();
        if (!$nav) {
            return Utils::api_response(404, '导航不存在');
        }

        Db::table('site_nav')->where('id', $id)->delete();
        return Utils::api_response(200, '删除成功');
    }

    // --- 模板 ---
    public static function upl_template() // 模板导入
    {
        if (!Utils::has_admin("template/upl")) {
            return false;
        }

        // 定义源文件夹和目标文件夹的路径
        $source_dir = '../view/' . Request::post('name') . '/static';
        $target_dir = './static';

        // 如果目标文件夹不存在，则创建它
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0777, true);
        }

        // 遍历源文件夹并复制文件到目标文件夹
        foreach (glob($source_dir . '/*') as $file) {
            if (is_file($file)) {
                copy($file, $target_dir . '/' . basename($file));
            }
        }

        return Utils::api_response(200, '模板导入成功');
    }

    // --- 设置 ---
    public static function php_info() // 获取phpinfo
    {
        if (!Utils::has_admin("settings/other/env")) {
            return false;
        }

        phpinfo();

        return '';
    }

    public static function get_db_info() // 获取数据库信息
    {
        if (!Utils::has_admin("settings/other/db")) {
            return false;
        }

        $db_name = env('DB_NAME', '');

        $result = Db::query("
        SELECT 
            table_name AS name, 
            SUM(table_rows) AS rows, 
            SUM(data_length + index_length) AS size
        FROM information_schema.tables
        WHERE table_schema = :db_name
        GROUP BY table_name;
        ", [
            'db_name' => $db_name
        ]);

        return Utils::api_response(200, '获取成功', $result);
    }

    // --- 高级 ---
    public static function get_all_pages() // 获取所有页面
    {
        if (!Utils::has_admin("high/group")) {
            return false;
        }
        $content = file_get_contents("../view/admin/pages.json");
        return Utils::api_response(200, '获取成功', json_decode($content));
    }
}
